<template>
  <div>
    <el-upload
      action="#"
      :auto-upload="false"
      :on-change="handleChange"
      :before-upload="beforeUpload"
      :limit="1"
      :on-exceed="handleExceed"
      :file-list="fileList"
    >
      <el-button type="primary">点击上传</el-button>
      <template #tip>
        <div class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
      </template>
    </el-upload>
    <el-button
      type="success"
      @click="submitUpload"
    >提交上传</el-button>
  </div>
</template>
<script>
import productApi from "@/api/product";
import request from "@/utils/request";
import axios from "axios";
export default {
  data() {
    return {
      fileList: [],
      formData: new FormData(),
    };
  },
  methods: {
    handleChange(file, fileList) {
      this.fileList = fileList;
    },
    beforeUpload(file) {
      // const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      // const isLt500KB = file.size / 1024 < 500;

      // if (!isJPG) {
      //   this.$message.error('上传图片只能是 JPG/PNG 格式!');
      // }
      // if (!isLt500KB) {
      //   this.$message.error('上传图片大小不能超过 500KB!');
      // }
      // return isJPG && isLt500KB;
      return true;
    },
    handleExceed(files, fileList) {
      this.$message.warning("只能上传一张图片");
    },
    async submitUpload() {
      if (this.fileList.length === 0) {
        this.$message.warning("请先选择图片");
        return;
      }
      console.log("fileList", this.fileList[0].raw);
      this.formData.append("file", this.fileList[0].raw);

      productApi.uploadImg(this.formData).then((res) => {});
      // const res = await request.postForm("http://localhost:8011/qiniu/uploadImg", {
      //   file: this.fileList[0].raw,
      // });
      // console.log('res',res)
      // productApi.uploadImg(this.formData)
      //   .then(response => {
      //     this.$message.success('上传成功');
      //     console.log('文件URL:', response.data);
      //   })
      //   .catch(error => {
      //     this.$message.error('上传失败');
      //     console.error('上传失败:', error);
      //   });
    },
  },
};
</script>
  
  <style scoped>
.el-upload__tip {
  margin-top: 10px;
  font-size: 12px;
  color: #606266;
}
</style>